package mn.idax.exchange.otc.util;

import com.google.common.collect.Maps;
import org.slf4j.LoggerFactory;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.util.Map;
import java.util.TreeMap;

/**
 * @Author jension
 * @Date Created in 14:11 2021/3/18
 */
public class SignUtils {

    private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(SignUtils.class);

    /**
     * 生成签名
     *
     * @param param
     * @param secret
     * @return
     */
    public static String generateSign(Map param, String secret) {
        param.remove("sign");
        String paramUrlStr = sortMap(param);
        return hmacSha256(paramUrlStr, secret);
    }


    /**
     * sha256_HMAC加密
     *
     * @param message 消息
     * @param secret  秘钥
     * @return 加密后字符串
     */
    public static String hmacSha256(String message, String secret) {
        String hash = "";
        try {
            String data = message;
            Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
            SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256");

            sha256_HMAC.init(secret_key);
            byte[] bytes = sha256_HMAC.doFinal(data.getBytes());
            hash = byteArrayToHexString(bytes);
        } catch (Exception e) {
            LOGGER.warn("hmacSha256 exception:" + e.getMessage());
        }
        return hash;
    }


    /**
     * 将加密后的字节数组转换成字符串
     *
     * @param b
     * @return
     */
    private static String byteArrayToHexString(byte[] b) {
        StringBuilder hs = new StringBuilder();
        String stmp;
        for (int n = 0; b != null && n < b.length; n++) {
            stmp = Integer.toHexString(b[n] & 0XFF);
            if (stmp.length() == 1) {
                hs.append('0');
            }
            hs.append(stmp);
        }
        return hs.toString().toLowerCase();
    }

    /**
     * sortMap
     *
     * @param paramMap
     * @return
     */
    public static String sortMap(Map<String, Object> paramMap) {
        TreeMap<String, Object> treeMap = new TreeMap(paramMap);
        StringBuffer strBuffer = new StringBuffer();
        for (String key : treeMap.keySet()) {
            strBuffer.append(key).append("=").append(paramMap.get(key)).append("&");

        }
        strBuffer.deleteCharAt(strBuffer.length() - 1);
        return strBuffer.toString();
    }

    public static void main(String[] args) {
        String secret = "jensionsecret";
        Map paramMap = Maps.newHashMap();
        paramMap.put("key", "jensionkey");
        paramMap.put("timeStamp", "1647750699000");
        paramMap.put("userId", "321");
        paramMap.put("sign", "qwe1");
        System.out.println(generateSign(paramMap, secret));
    }

}
